#!/bin/bash

# The following utils should be available/installed: awk, unzip, 7z, base64

FLIBUSTA_PATH=/home/user/books/fb2.Flibusta.Net.7z
INPX_NAME=flibusta_fb2_local.inpx

usage() {
    echo " $(basename $0) -a author | -t title | -x extract"
    exit
}

if [ $# -ne 2 ]; then
    usage
fi

if [ $1 != "-a" ] && [ $1 != "-t" ] && [ $1 != "-x" ]; then
    usage
fi

case "$1" in
"-a")
    AUTHOR="${2// /}"
    ;;
"-t")
    TITLE="${2// /}"
    ;;
"-x")
    EXTRACT=$2
    ;;
*)
    usage
    ;;
esac

# Unzip index files if not done before
[ ! -d "$FLIBUSTA_PATH/index" ] && unzip -o "$FLIBUSTA_PATH/$INPX_NAME" -d "$FLIBUSTA_PATH/index"

if [ "$AUTHOR" != "" ] || [ "$TITLE" != "" ]; then
    echo "FILENAME|FILEID|AUTHOR|GENRE|TITLE|SERIES|SERNO|SIZE|LIBID|DEL|EXT|DATE|LANG|KEYWORDS"
fi

if [ "$AUTHOR" != "" ]; then
    cd $FLIBUSTA_PATH/index
    awk -v toSearch=$AUTHOR '{ woSp=$1; gsub(/[ \t]+/, "", woSp); file7z=FILENAME; sub(/\.inp$/, ".7z", file7z); if(index(tolower(woSp), tolower(toSearch))) print file7z,$6,$1,$2,$3,$4,$5,$7,$8,$9,$10,$11,$11,$12,$13 }' FS="\x4" OFS="|" *.inp
fi

if [ "$TITLE" != "" ]; then
    cd $FLIBUSTA_PATH/index
    awk -v toSearch=$TITLE '{ woSp=$3; gsub(/[ \t]+/, "", woSp); file7z=FILENAME; sub(/\.inp$/, ".7z", file7z); if(index(tolower(woSp), tolower(toSearch))) print file7z,$6,$1,$2,$3,$4,$5,$7,$8,$9,$10,$11,$11,$12,$13 }' FS="\x4" OFS="|" *.inp
fi

if [ "$EXTRACT" != "" ]; then
    FILENAME=$(echo $EXTRACT | awk '{ print $1 }' FS="|")
    FILEID=$(echo $EXTRACT | awk '{ print $2 }' FS="|")
    AUTHORSTR=$(echo $(echo $EXTRACT | awk '{ print $3 }' FS="|") | tr -d '[:space:]' | tr -d '[()]')
    TITLESTR=$(echo $(echo $EXTRACT | awk '{ print $5 }' FS="|") | tr -d '[:space:]' | tr -d '[()]')
    NEW_FILE_NAME="$AUTHORSTR$TITLESTR.fb2"
    EXTRACTCMD="7z -aoa x $FLIBUSTA_PATH/$FILENAME -so $FILEID.fb2 > $NEW_FILE_NAME"
    echo $EXTRACTCMD
    eval $EXTRACTCMD

    FILENAMEZIP=$(echo $FILENAME | awk '{ print $1 }' FS=".7z").zip

    # Exit if there are no image archive
    [ ! "$FILENAMEZIP" ] && exit

    UNZIPCMD="unzip -oq $FLIBUSTA_PATH/images/$FILENAMEZIP \"$FILEID/*\" &> /dev/null"
    echo $UNZIPCMD
    eval $UNZIPCMD

    # Exit if there are no image directory inside of the archive
    [ ! -d "$FILEID" ] && exit

    for file in $FILEID/*;
    do
        BASE64STR=`base64 $file`;
        IMAGE_FILE=$(echo $file | awk '{ print $2 }' FS="/")
        echo " <binary id=\"$IMAGE_FILE\" content-type=\"image\">$BASE64STR</binary>" >> $FILEID.images
    done;
    sed -i "s|</FictionBook>||g" $NEW_FILE_NAME;
    cat $FILEID.images >> $NEW_FILE_NAME
    echo "</FictionBook>" >> $NEW_FILE_NAME
    rm -r $FILEID $FILEID.images
fi

